import json
import os
import requests
import sys

import util

url = os.getenv('JIANMU_BOOT_WEBHOOK_URL')
secret = os.getenv('JIANMU_SECRET')
signs = util.get_signature(secret)
title = os.getenv('JIANMU_MSG_TITLE')
text = os.getenv('JIANMU_MSG_TEXT')
single_title = os.getenv('JIANMU_SINGLE_TITLE')
single_url = os.getenv('JIANMU_SINGLE_URL')
btns_str = os.getenv('JIANMU_BTNS')
btn_orientation = os.getenv('JIANMU_BTN_ORIENTATION')

headers = {
    'Content-Type': 'application/json'
}
params = {
    'sign': signs.get('sign'),
    'timestamp': signs.get('timestamp'),
}

try:
    btns = json.loads(btns_str if btns_str else '[]')
except Exception as e:
    print('error: 参数btns格式错误，如：\'[{"title": "建木","actionURL": "https://jianmu.dev/"}]\'')
    sys.exit(1)
data = {
    'msgtype': 'actionCard',
    'actionCard': {
        "title": title,
        "text": text,
        "singleTitle": single_title,
        "singleURL": single_url,
        "btnOrientation": btn_orientation,
        "btns": btns
    }
}
response = requests.post(url=url, headers=headers, params=params, data=json.dumps(data))
content = response.json()
if content.get("errcode") != 0:
    raise Exception(content)
print(content)
